package com.xiaozhu.server.Impl;

import com.xiaozhu.common.aiconstant.LockConstants;
import com.xiaozhu.enumreation.LockState;
import com.xiaozhu.enumreation.RedisKeyEnum;
import com.xiaozhu.enumreation.RoleRedisEnum;
import com.xiaozhu.mapper.ChatContentMapper;
import com.xiaozhu.mapper.ChatSessionMapper;
import com.xiaozhu.pojo.entity.ChatSession;
import com.xiaozhu.repository.ChatSessionHistoryRepository;
import com.xiaozhu.server.ChatContentServer;
import com.xiaozhu.utils.RedisLockTemplate;
import com.xiaozhu.utils.RedisUtils;
import jdk.jfr.Threshold;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class ChatContentServerImpl implements ChatContentServer {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private ChatContentMapper chatContentMapper;

    @Autowired
    private ChatSessionMapper chatSessionMapper;

    @Autowired
    private RedisLockTemplate redisLockTemplate;

    @Override
    public String content(Integer chatTypeId) {


        log.info("进入数据库中查序：{}", chatTypeId);
        // 查询该类型下的所有聊天会话
        List<ChatSession> sessions = chatSessionMapper.chatSession(chatTypeId);
        if (sessions.isEmpty()) {
            log.info("数据库中也没有聊天内容");
            return "暂无聊天内容";
        }

        StringBuilder result = new StringBuilder();

        Integer id = sessions.get(sessions.size() - 1).getId();

        log.info("id:{}, user:{}, model；{}", id, RoleRedisEnum.ROLE_USERC.getName(), RoleRedisEnum.ROLE_MODEL.getName());

        // 查询用户与模型的内容
        List<String> userContent = chatContentMapper.chatContent(id, RoleRedisEnum.ROLE_USERC.getName());
        List<String> modelContent = chatContentMapper.chatContent(id, RoleRedisEnum.ROLE_MODEL.getName());

        // 将查询的数据回填的redis中

        String keyUser = RedisKeyEnum.REDIS_KEY_CONTENT.keyTyp() + RoleRedisEnum.ROLE_USERC.getName();

        String keyModel = RedisKeyEnum.REDIS_KEY_CONTENT.keyTyp() + RoleRedisEnum.ROLE_MODEL.getName();

        // 构建锁的名称
        String key = LockConstants.LOCKED_KEY + chatTypeId;

        // 构建当前锁的唯一标识，哪一个会话的锁
        String requested = chatTypeId.toString();

        redisLockTemplate.executeWithLock(key,requested, () ->{
            // 这里需要根据会话id进行分类存储，不然会全部会话历史都是全部一样的内容，需要添加分布锁，防止堵塞
            redisUtils.set(keyUser, userContent);
            redisUtils.set(keyModel, modelContent);
            // 无需返回值
            return null;
        });


        result.append("【会话ID: ")
                .append(id)
                .append(" 用户: ")
                .append(userContent != null ? userContent : "(空)")
                .append("模型: ")
                .append(modelContent != null ? modelContent : "(空)");

        log.info("数据库内容：{}", result);


        return result.toString();
    }
}
